package com.video.moderation.utils;

import com.video.moderation.constant.SecurityConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
@Component
public class JwtUtils {
    
    // 过期时间：天
    @Value("${cc-video.moderation.jwt.expire}")
    private int expire;

    // 密钥
    @Value("${cc-video.moderation.jwt.secret}")
    private String secret;

    public String generateJwtToken(Integer memberId, String memberNum) {
        // 密钥实例(密钥应该大于等于 256位(长度32及以上的字符串)，并且是随机的字符串)
        SecretKey secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        LocalDateTime expireTime = LocalDateTime.now().plusDays(expire);

        Map<String,Object> claim = new HashMap<>();
        claim.put(SecurityConstants.MEMBER_ID, memberId);
        claim.put(SecurityConstants.MEMBER_NUM, memberNum);
        
        return Jwts.builder()
                .header().add("typ", "JWT").and()
                .expiration(Timestamp.valueOf(expireTime))
                .issuedAt(Timestamp.valueOf(LocalDateTime.now()))
                .signWith(secretKey, Jwts.SIG.HS256)
                .claims(claim)
                .compact();
    }
    
    public Claims getClaims(String token) {
        SecretKey secretKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
        return Jwts.parser()
                .verifyWith(secretKey)
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }
    
    public boolean isExpire(Date expireDate) {
        return expireDate.before(new Date());
    }
    
}
